/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.evote.monitoreo.ejb;

import com.evote.monitoreo.entity.Locacion;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

/**
 *
 * @author Mendoza
 */
@Stateless
@LocalBean
public class MonitoreoSessionBean {
    @Resource(name = "jms/MonitoreoNotificationBean")
    private Queue monitoreoNotificationBean;
    @Resource(name = "jms/MonitoreoNotificationBeanFactory")
    private ConnectionFactory monitoreoNotificationBeanFactory;
    
    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")

    public Double getAlreadyVotedProportion() {
        return 3.14159;
    }

    public Integer getTotalVoters() {
        return 2;
    }

    public Integer countAlreadyVoted() {
        return 1;
    }

    public Integer countVotersInSession() {
        return 0;
    }

    public List<Locacion> getLocations() {
        // test list
        Locacion testLocation = new Locacion();
        testLocation.setIdLocacion(1);
        List<Locacion> testList = new ArrayList<Locacion>();
        testList.add(testLocation);
        return testList;
    }

    public Integer countVotersByLocacion( Locacion terminal ) {
        return 1;
    }

    private Message createJMSMessageForjmsMonitoreoNotificationBean(Session session, Object messageData) throws JMSException {
        // TODO create and populate message to send
        TextMessage tm = session.createTextMessage();
        tm.setText(messageData.toString());
        return tm;
    }

    private void sendJMSMessageToMonitoreoNotificationBean(Object messageData) throws JMSException {
        Connection connection = null;
        Session session = null;
        try {
            connection = monitoreoNotificationBeanFactory.createConnection();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(monitoreoNotificationBean);
            messageProducer.send(createJMSMessageForjmsMonitoreoNotificationBean(session, messageData));
        } finally {
            if (session != null) {
                try {
                    session.close();
                } catch (JMSException e) {
                    Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Cannot close session", e);
                }
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
 
}
